package Util;

/*
 * Copyright 2013 Fabian Gilson. This file is part of Online Library academic project and it is free software: you can redistribute it and/or modify it under the
 * terms of the GNU General Public License version 3 as published by the Free Software Foundation. It is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details. see <http://www.gnu.org/licenses/>.
 */

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.util.ArrayList;

import BookStore.common.Book;

/**
 * This class parses a CSV file containing books and fill in Book structure
 * classes
 * 
 * @see org.onlinelibrary.parser.Book
 * @author Fabian Gilson
 */
public class CSVBookParser {

	/**
	 * Get the catalog of a book store
	 * 
	 * @param csv
	 *            CSV file containing the book store catalog
	 * @return the catalog
	 */
	public Book[] getCatalog(String csv) {

		BufferedReader r = this.open(csv, Charset.forName("UTF-8"));

		Book[] list = this.parse(r);
		try {
			r.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return list;
	}

	/**
	 * Default constructor
	 * 
	 * 
	 */
	public CSVBookParser() {
		super();

	}

	/**
	 * Constructor
	 * 
	 * @param log4j
	 *            path to log4j properties file
	 * @throws FileNotFoundException
	 *             if log4j property file is not found
	 */
	public CSVBookParser(String log4j) throws FileNotFoundException {
		super();
	}

	/**
	 * Open the CSV file
	 * 
	 * @param file
	 *            the path (full or relative) to the CSV file
	 * @param charset
	 *            the character set of the CSV file
	 * @return the reader opened at the beginning of the file, null if the file
	 *         does not exist
	 */
	public BufferedReader open(String file, Charset charset) {
		try {
			BufferedReader buffer = new BufferedReader(new InputStreamReader(
					new FileInputStream(file), charset));
			return buffer;
		} catch (FileNotFoundException e) {
			return null;
		}
	}

	/**
	 * Parse the whole CSV file from the given reader and returns an array of
	 * books
	 * 
	 * @param reader
	 *            reader opened on a CSV file
	 * @return an array of books
	 * @see org.onlinelibrary.parser.Book
	 */
	public Book[] parse(BufferedReader reader) {
		ArrayList<Book> books = new ArrayList<Book>();
		try {
			while (reader.ready()) {
				books.add(parseLine(reader));
			}
		} catch (IOException e) {
			// do nothing, just return what we read until now (can be empty)
		}
		return books.toArray(new Book[books.size()]);
	}

	/**
	 * Parse one line from CSV file from given reader
	 * 
	 * @param reader
	 *            reader opened on a CSV file
	 * @return the read book or null if a field of the book is invalid
	 * @see org.onlinelibrary.parser.Book
	 * 
	 */
	public Book parseLine(BufferedReader reader) {
		String read;
		String[] values;
		Book book = null;
		try {
			if ((read = reader.readLine()) != null) {
				values = read.split(";");

				book = new Book(values[3], values[0], values[1], values[2],
						Float.parseFloat(values[4]),
						Float.parseFloat(values[5]));
			}
		} catch (Exception e) {
			// ignore this line
			System.out.println("exception");
			e.printStackTrace();
		}
		return book;
	}

	/**
	 * Write a textual content in a file
	 * 
	 * @param fileContent
	 *            textual content to write
	 * @param filePathOutput
	 *            file path
	 * @return true if the writing succeeded, otherwise false
	 */
	public static boolean writeFile(String fileContent, String filePathOutput) {
		try {

			PrintWriter output = new PrintWriter(new FileWriter(filePathOutput,
					true));

			output.println(fileContent);
			output.flush();
			output.close();
		} catch (IOException ioe) {
			return false;
		}
		return true;
	}

	/**
	 * Get the numbers of lines of a csv file
	 * @param csv file
	 * @return the number of lines
	 */
	public int getNumberOfLines(String csv) {

		BufferedReader reader;
		int i = 0;
		reader = this.open(csv, Charset.forName("UTF-8"));
		if (reader != null) {
			try {
				while (reader.ready()) {
					reader.readLine();
					i++;
				}
			} catch (Exception e) {
				// error
			}
		}

		return i;
	}

}
